﻿using Blog.Core.Entity;
using Blog.Core.Service;
using Nancy;
using Nancy.Extensions;
using Nancy.ModelBinding;
using System;

namespace Web.Module
{
    public class AdminCategoryModule : AdminModule
    {
        public AdminCategoryModule()
        {
            Get["/categorys/add"] = p => View["addcategory"];

            Post["/categorys/add"] = _ =>
            {
                var model = this.Bind<PostCategory>();
                return AddCategory(model);
            };

            Get["/categorys/edit/{id}"] = p => EditCategory(p.id);

            Post["/categorys/edit"] = p =>
            {
                var model = this.Bind<PostCategory>();
                return EditCategory(model);
            };

            Get["/categorys"] = _ => Categorys();

            Get["/categorys/del/{id:int}"] = p => DelCategory(p.id);

        }

        public dynamic Categorys()
        {
            var list = PostCategory.Fetch("");
            return View["categorys", list];
        }

        public dynamic EditCategory(int id)
        {
            var model = Blog.Core.Entity.PostCategory.SingleOrDefault(id);
            return View["editcategory", model];
        }

        public string EditCategory(PostCategory model)
        {
            model.Update();
            return "{\"status\":\"y\",\"msg\":\"修改成功，稍后将刷新页面！\",\"url\":\"/sean/categorys\"}";
           // return Context.GetRedirect("/sean/categorys");
        }

        public string AddCategory(PostCategory model)
        {
            model.Insert();
            return "{\"status\":\"y\",\"msg\":\"添加成功，稍后将刷新页面！\",\"url\":\"/sean/categorys\"}";
        }

        public dynamic DelCategory(int id)
        {
            Blog.Core.Entity.PostCategory.repo.Execute("DELETE FROM [PostCategory] WHERE Id=@0", id);
            return Context.GetRedirect("/sean/categorys");
        }
    }
}